package com.stone.action;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.stone.model.Admin;
import com.stone.model.Project;
import com.stone.model.Stone;
import com.stone.service.ILoggerService;
import com.stone.service.IProjectService;
import com.stone.service.IStoneService;
import com.stone.serviceimpl.LoggerService;
import com.stone.utils.LogConstrants;
import com.stone.utils.Page;

public class ProjectAction extends ActionSupport {
	/**
	 * 
	 */
	private static final long serialVersionUID = -6452639454128637530L;
	private IProjectService projectService ;
	private IStoneService stoneService;
	private ILoggerService logService = new LoggerService();
	
	private Long projectId;
	private Project project;
	private File iconFile;
	private String uploadDir; //上传头像的路径
	private String iconFileName; //文件尾坠
	private String changeImageFlag = "no";
	
	private Page page;		//分页显示所用的page bean
	private Integer pageNo = 1;
	private Integer pageSize = 20;
	private int pageno;
	private int totalpageno;
	private int currentpageno;
	private String query;
	private boolean mainSearch;
	private boolean hasQueue = false;
	/*Max Number Of Recently Visit Stone*/
	private final int MAXRECENTLY = 3;
	
	private static Logger logger = Logger.getLogger("精品工程");
	
	//-----------DETAIL ACTION
	public String saveProject(){
		/*
		 *	取得图片 保存图片 
		 */
		try {
			project.setPhoto(uploadIcon());
		} catch (IOException e) {
			e.printStackTrace();
		}
		projectService.addProject(project);
		Map<String, Object> session = ActionContext.getContext().getSession();
		logger.fatal(((Admin)session.get("admin")).getUsername()+"添加了精品工程: "+project.getTitle());
		logService.log(((Admin)session.get("admin")).getUsername(), "添加了精品工程: " + project.getTitle(), LogConstrants.PROJECT_ADD);
		return SUCCESS;
	}
	
	public String toUpdateProject(){
		project = projectService.findProjectById(projectId);
		return SUCCESS;
	}
	public String updateProject(){
		
		if(changeImageFlag.equals("yes")){
			try {
				project.setPhoto(uploadIcon());
			} catch (IOException e) {
				e.printStackTrace();
			}
		}else{
			//do nothing;
		}
		projectService.updateProject(project);
		Map<String, Object> session = ActionContext.getContext().getSession();
		logger.fatal(((Admin)session.get("admin")).getUsername()+"更新了精品工程: "+project.getTitle());
		logService.log(((Admin)session.get("admin")).getUsername(), "更新了精品工程: " + project.getTitle(), LogConstrants.PROJECT_UPDATE);
		return SUCCESS;
	}
	
	/**
	 * 上传的文件 返回其文件名
	 * @return
	 * @throws IOException 
	 */
	public String uploadIcon() throws IOException{
		if(iconFile != null){
			String fileName =  System.currentTimeMillis()+iconFileName;	//设置名字
			
			BufferedOutputStream bos = null; //文件输出流
		    BufferedInputStream bis = null; //文件输入流
		    FileInputStream fis = new FileInputStream(iconFile);
			bis = new BufferedInputStream(fis);
			String outPath = ServletActionContext.getServletContext().getRealPath(uploadDir);
			FileOutputStream fos = new FileOutputStream(new File(outPath,fileName));
			bos = new BufferedOutputStream(fos);
	
			byte[] buf = new byte[1024*10];
	
			int len = -1;
			while ((len = bis.read(buf)) != -1) {
				bos.write(buf, 0, len);
			}
			buf = null;
			bos.flush();
			bos.close(); //关闭输出流
			bis.close(); //关闭输入流
			return fileName;
		}else{
			return "none";
		}
	}
	
	public String findProject(){
		project = projectService.findProjectById(projectId);
		return SUCCESS;
	}
	
	public String findProjectsByPage(){
		page = projectService.findAllProject(pageNo, pageSize);
		return SUCCESS;
	}
	
	public String deleteProject(){
		projectService.deleteProject(projectService.findProjectById(projectId));
		Map<String, Object> session = ActionContext.getContext().getSession();
		logger.fatal(((Admin)session.get("admin")).getUsername()+"删除了精品工程: id="+projectId);
		//logService.log(((Admin)session.get("admin")).getUsername(), "删除了精品工程: " + project.getTitle(), LogConstrants.PROJECT_UPDATE);
		return SUCCESS;
	}
	/**
	 * 
	 * @return
	 */
	public String searchProject(){
		if(this.pageno!=1){
			this.pageno=getPageNo(this.pageno,this.totalpageno);
		}	
		try {
			if(!mainSearch)
				this.query = new String(ServletActionContext.getRequest().getParameter("query").getBytes("ISO-8859-1"),"UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		page=this.projectService.searchProjectOrderByTitle(query,pageno, pageSize);
		this.totalpageno=page.getTotalPages();
		this.currentpageno=page.getCurrentPage();	
		setQueue();
		checkPopular();
		return "success";
	}
	/**
	 * 通过页面传来的pageno来决定当前页数
	 * @param pageNo
	 * @param totalpageno
	 * @return
	 */
	public int getPageNo(int pageNo,int totalpageno){
		if(pageNo>totalpageno){
			pageNo = totalpageno;
		}
		if(pageNo<=0){
			return 1;
		}
		return pageNo;
	}
	/**
	 *  check whether the popular stones are in the session 
	 */
	private void checkPopular(){
		Map session = ActionContext.getContext().getSession();
		if(session.get("popular")==null){
			//List<Stone> popularStones = stoneService.getVisitMostStones(1, 6).getList();
			List<Stone> popularStones = stoneService.getVisitMostDisplayStones(1, 6).getList();
			session.put("popular", popularStones);
		}
	}
	/**
	 * Get Visit Stone from Session Scop
	 */
	private void setQueue(){
		Map session = ActionContext.getContext().getSession();
		Queue<Stone> queue = (Queue<Stone>)session.get("recent");
		if(queue==null){
			queue = new ArrayBlockingQueue<Stone>(MAXRECENTLY);
			session.put("recent", queue);
		}
		hasQueue = (queue.size()>0)?true:false;
	}
	//------------SET GET
	public IProjectService getProjectService() {
		return projectService;
	}
	public void setProjectService(IProjectService projectService) {
		this.projectService = projectService;
	}
	public Project getProject() {
		return project;
	}
	public void setProject(Project project) {
		this.project = project;
	}
	public File getIconFile() {
		return iconFile;
	}
	public void setIconFile(File iconFile) {
		this.iconFile = iconFile;
	}
	public Page getPage() {
		return page;
	}
	public void setPage(Page page) {
		this.page = page;
	}
	public Integer getPageNo() {
		return pageNo;
	}
	public void setPageNo(Integer pageNo) {
		this.pageNo = pageNo;
	}
	public Integer getPageSize() {
		return pageSize;
	}
	public void setPageSize(Integer pageSize) {
		this.pageSize = pageSize;
	}
	public String getUploadDir() {
		return uploadDir;
	}
	public void setUploadDir(String uploadDir) {
		this.uploadDir = uploadDir;
	}
	public String getIconFileName() {
		return iconFileName;
	}
	public void setIconFileName(String iconFileName) {
		this.iconFileName = iconFileName;
	}
	public Long getProjectId() {
		return projectId;
	}
	public void setProjectId(Long projectId) {
		this.projectId = projectId;
	}

	public int getPageno() {
		return pageno;
	}

	public void setPageno(int pageno) {
		this.pageno = pageno;
	}

	public int getTotalpageno() {
		return totalpageno;
	}

	public void setTotalpageno(int totalpageno) {
		this.totalpageno = totalpageno;
	}

	public String getQuery() {
		return query;
	}

	public void setQuery(String query) {
		this.query = query;
	}

	public int getCurrentpageno() {
		return currentpageno;
	}
	public void setMainSearch(boolean mainSearch) {
		this.mainSearch = mainSearch;
	}
	public void setStoneService(IStoneService stoneService) {
		this.stoneService = stoneService;
	}
	public boolean isHasQueue() {
		return hasQueue;
	}

	public String getChangeImageFlag() {
		return changeImageFlag;
	}

	public void setChangeImageFlag(String changeImageFlag) {
		this.changeImageFlag = changeImageFlag;
	}

	public IStoneService getStoneService() {
		return stoneService;
	}
}
